<template>
  <div class="basic-wrap">
    <div class="button-wrap">
      <a-space>
        <a-button type="primary" @click="showAddAsset">新增</a-button>
        <a-button type="primary" @click="handleShowOutbound">出库</a-button>
        <!--        <a-button type="primary" @click="handleShowTransfer">调拨</a-button>-->
        <a-button @click="handleImport">导入</a-button>
      </a-space>
      <div class="right-button-wrap">
        <a-space>
          <a-checkbox v-model:checked="so.onlyBind">只看已绑定EPC资产</a-checkbox>
          <a-input v-model:value="so.keyword" placeholder="关键词查询"
                   style="width:160px">
            <template #prefix>
              <SearchOutlined style="color:#666"/>
            </template>
          </a-input>
          <a-button type="primary" @click="reload">查询</a-button>
        </a-space>
      </div>
    </div>
    <div class="table-wrap">
      <a-table
        :loading="loading"
        size="middle"
        :dataSource="dataSource"
        :columns="columns"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'inventoryStatus'">

            <a-tag v-if="record.inventoryStatus == 1" color="blue">在库</a-tag>
            <a-tag v-else-if="record.inventoryStatus == 2" color="orange">多盘</a-tag>
            <a-tag v-else color="red">未盘点</a-tag>
          </template>
          <template v-if="column.key === 'operation'">
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleDetail(record)"
            >
              查看
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleDelete(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
    <!--    <add-asset :open="openAddAsset" @handleSubmit="handleSubmit"></add-asset>-->
    <a-modal
      v-model:visible="openAddAsset"
      title="新增资产"
      width="480px"
      @ok="handleSubmit"
    >
      <a-form
        ref="formRef"
        style="margin-top: 24px"
        :model="formState"
        name="basic"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 17 }"
        autocomplete="off"
      >
        <a-form-item
          label="资产名称"
          name="assetName"
          :rules="[
            { required: true, message: 'Please input your contractName!' },
          ]"
        >
          <a-input
            readOnly
            onfocus="this.removeAttribute('readonly');"
            onblur="this.setAttribute('readonly',true);"
            v-model:value="formState.assetName"
          />
        </a-form-item>
        <a-form-item
          label="资产编号"
          name="assetCode"
          :rules="[
            { required: true, message: 'Please input your contractName!' },
          ]"
        >
          <a-input
            readOnly
            onfocus="this.removeAttribute('readonly');"
            onblur="this.setAttribute('readonly',true);"
            v-model:value="formState.assetCode"
          />
        </a-form-item>
        <a-form-item
          label="所属用户"
          name="clientId"
          v-bind:class="{ hidden: isHidden }"
          :rules="[{ required: true, message: 'Please input your userId!' }]"
        >
          <!--          <a-input-->
          <!--            readOnly-->
          <!--            onfocus="this.removeAttribute('readonly');"-->
          <!--            onblur="this.setAttribute('readonly',true);"-->
          <!--            v-model:value="formState.clientId"-->
          <!--          />-->
          <a-select
            ref="select"
            v-model:value="formState.clientId"

            @focus="focus"
            @change="handleChangeClient"
          >
            <a-select-option
              v-for="item in clientList"
              :key="item.id"
              :value="item.id"
            >{{ item.clientName }}
            </a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="所在楼层" name="assetFloor">
          <a-auto-complete
            v-model:value="formState.floorName"
            :options="floorOptions"
            style="width: 100%"
            @select="onSelectFloor"
            @search="onSearchFloor"
          />
        </a-form-item>
        <a-form-item label="所在房间" name="assetPosition">
          <a-auto-complete
            v-model:value="formState.positionName"
            :options="positionOptions"
            style="width: 100%"
            @select="onSelectPosition"
            @search="onSearchPosition"
          />
        </a-form-item>
        <a-form-item label="位置详情" name="address">
          <a-input
            readOnly
            onfocus="this.removeAttribute('readonly');"
            onblur="this.setAttribute('readonly',true);"
            v-model:value="formState.address"
          />
        </a-form-item>
        <a-form-item label="资产照片" name="assetImage">
          <a-upload
            v-model:file-list="fileList"
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 1"></div>
          </a-upload>
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-input
            readOnly
            onfocus="this.removeAttribute('readonly');"
            onblur="this.setAttribute('readonly',true);"
            v-model:value="formState.remark"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="openImport"
      title="导入资产"
      width="480px"
      @ok="handleImportSubmit"
    >
      <div>
        <div v-bind:class="{ hidden: isHidden }">
          所属客户
          <a-select
            ref="select"
            v-model:value="importClient"
            style="width: 120px; margin-left: 8px"
            @focus="focus"
            @change="handleClientChange"
          >
            <a-select-option
              v-for="item in clientList"
              :key="item.id"
              :value="item.id"
            >{{ item.clientName }}
            </a-select-option
            >
          </a-select>
        </div>

      </div>
      <a-upload-dragger
        style="margin-top: 8px"
        v-model:fileList="fileList"
        name="file"
        :data="{ clientId: importClient }"
        :headers="{ authorization: `Bearer ${accessStore.accessToken}` }"
        :multiple="flase"
        :limit="1"
        action="/api/asset/importExcel"
        @change="handleUploadChange"
        @drop="handleDrop"
      >
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <p class="ant-upload-text">Click or drag file to this area to upload</p>
        <p class="ant-upload-hint">
          Support for a single or bulk upload. Strictly prohibit from uploading
          company data or other band files
        </p>
      </a-upload-dragger>
      <a-button type="link" size="mini" @click="handleDownTamplete">下载导入模板</a-button>
    </a-modal>

    <transfer-asset :open="openTransfer" @close="closeTransfer" :key="refreshKey"></transfer-asset>
    <lifecycle :open="openLifecycle" @close="closeLifecycle" :key="refreshKey"
               :asset="targetAsset"></lifecycle>
    <outbound :open="openOutbound" @close="closeOutbound" :key="refreshKey"></outbound>

  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref, unref, watch} from 'vue';
import type {FormInstance} from 'ant-design-vue';
import {message} from 'ant-design-vue';
import type {Dayjs} from 'dayjs';
import dayjs from 'dayjs';
import type {AssetBo, AssetPageVo, AssetSo, ClientVo, FloorVo, PositionVo} from '#/api/common';
import {useAccessStore, useUserStore} from '@vben/stores';
import {addAssetApi, listClientApi, listFloorApi, listPositionApi, pageAssetApi} from '#/api';
import {InboxOutlined, SearchOutlined} from "@ant-design/icons-vue";
import TransferAsset from './components/TransferAsset.vue'
import Lifecycle from './components/Lifecycle.vue'
import Outbound from './components/Outbound.vue'


const accessStore = useAccessStore();
const userStore = useUserStore();
const keyword = ref<string>('');
const assetType = ref<string>('');
const refreshKey = ref<string>('');
const dataSource = ref<AssetPageVo[]>([]);
const clientList = ref<ClientVo[]>([]);
const floorList = ref<FloorVo[]>([]);
const positionList = ref<PositionVo[]>([]);
const options1 = ref<{ value: string }[]>([]);
type RangeValue = [Dayjs, Dayjs];
const searchDate = ref<RangeValue>();
const dateValue = ref<Dayjs>();
const loading = ref(false);
const open = ref(false);
const openFiles = ref(false);
const formRef = ref<FormInstance>();
const fileList = ref([]);
const openAddAsset = ref(false);
const openImport = ref(false);
const openTransfer = ref(false);
const openLifecycle = ref(false);
const openOutbound = ref(false);
const targetAsset = ref<AssetPageVo>({});

console.log('userStore', userStore.userRoles)
const onlyBind = ref<boolean>(false);
// const isHidden = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const importClient = ref('');
const curClientId = ref<string | undefined>('');
const floorOptions = ref<{ value: string }[]>([])
const positionOptions = ref<{ value: string }[]>([])

let currentContractId = ref<string>('');

const ADMIN_LIST = ['ADMIN', 'SUPER_ADMIN']

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 15,
  size: '',
  showSizeChanger: false,
  showQuickJumper: false,
});
const so = reactive<AssetSo>({
  keyword: '',
  clientId: '',
  floorId:'',
  positionId:'',
  onlyBind: false
})
const pageParam = computed(() => ({
  query: unref(so),
  current: pagination.value?.current,
  size: pagination.value?.pageSize,
}));

const isAdmin = computed(() => {
  return userStore.userRoles.some(element => ADMIN_LIST.includes(element));
})

// const floorOptions = computed(() => {
//   return floorList.value.map(s => {
//     return {
//       value: s.floor
//     }
//   })
// })

const columns = [
  {
    title: '资产编码',
    dataIndex: 'assetCode',
    key: 'assetCode',
    width: 180,
    align: 'center',
  },
  {
    title: '资产名称',
    dataIndex: 'assetName',
    key: 'contractName',
    align: 'center',
  },
  {
    title: 'EPC芯片码',
    dataIndex: 'assetEpc',
    key: 'assetEpc',
    width: 240,
    align: 'center',
  },
  {
    title: '所属客户',
    dataIndex: 'clientName',
    key: 'clientName',
    width: 200,
    align: 'center',
  },
  {
    title: '资产位置',
    dataIndex: 'address',
    key: 'address',
    width: 240,
    align: 'center',
  },
  {
    title: '盘点状态',
    dataIndex: 'inventoryStatus',
    key: 'inventoryStatus',
    width: 140,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 160,
    align: 'center',
  },
];

onMounted(() => {
  list();
  listClient();
  console.log('isAdmin', isAdmin)
});

watch(dateValue, (newValue, oldValue) => {
  console.log(`新值: ${newValue}, 旧值: ${oldValue}`);
  formState.contractDate = dayjs(newValue).format('YYYY-MM-DD');
});

let formState = reactive<AssetBo>({
  assetName: '',
  assetCode: '',
  clientId: '',
  floorName: '',
  positionName: '',
  address: '',
  assetImage: '',
  remark: '',
});

const handleSubmit = () => {
  console.log('formState', formState)
  formRef.value
    ?.validateFields()
    .then(() => {
      addAssetApi(formState).then(() => {
        message.success('添加成功');
        list();
        openAddAsset.value = false;
      });
    })
    .catch((e) => {
      console.log('表单错误', e);
      message.error('表单填写错误');
    });
};

async function list() {
  loading.value = true;
  const res = await pageAssetApi(unref(pageParam));
  dataSource.value = res.records;
  pagination.value.total = Number(res.total);
  pagination.value.current = Number(res.current);
  loading.value = false;
}

const handleAddSubmit = () => {
  formRef.value
    ?.validateFields()
    .then(() => {
      // formState.files = fileResultList.value;
      // console.log('fileResultList', fileResultList);
      console.log('formState', formState);
      uploadContractApi(formState).then(() => {
        message.success('上传成功');
      });
      // addUser(formState).then(() => {
      //   message.success('添加成功')
      //   open.value = false
      //   list()
      // })
    })
    .catch((e) => {
      console.log('表单错误', e);
      message.error('表单填写错误');
    });
};
const handleUploadChange = (info: UploadChangeParam) => {
  console.log('handleChange info', info);
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} 导入成功`);
    openImport.value = false
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

const handleShowFile = (record) => {
  refreshKey.value = Math.random();
  currentContractId.value = record.id;
  openFiles.value = true;
};

const reload = () => {
  pagination.value.current = 1;
  list();
}

function handleTableChange(page) {
  pagination.value.current = page.current;
  list();
}

const handleImport = () => {
  listClient();
  openImport.value = true;
};
const handleImportSubmit = () => {
  console.log('handleImportSubmit');
  openImport.value = true;
};

async function listClient() {
  clientList.value = await listClientApi();
  if (isAdmin) {
    console.log('clientList', clientList.value[0]?.id)
    curClientId.value = clientList.value[0]?.id
    formState.clientId = clientList.value[0]?.id
    if (curClientId.value) {
      loadFloor()
    }
  }
}

const handleDrop = () => {
  if (importClient.value == '') {
    message.error('请先选择客户');
    return;
  }
};
const handleShowTransfer = () => {
  refreshKey.value = Math.random() * 10000
  console.log('refreshKey.value ', refreshKey.value)
  openTransfer.value = true
}
const closeTransfer = () => {
  openTransfer.value = false
}
const closeLifecycle = () => {
  openLifecycle.value = false
}
const closeOutbound = () => {
  openOutbound.value = false
  reload()
}
const handleDownTamplete = () => {
  window.open("http://kingtown-contract-test.oss-cn-shanghai.aliyuncs.com/public/%E9%94%A6%E5%94%90%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx")
}
const onSearchFloor = (searchText: string) => {
  console.log('onSearchFloor', searchText);
  floorOptions.value = floorList.value.filter(s => s.floor.indexOf(searchText) > -1).map(s => {
    console.log('target floor', s)
    return {value: s.floor}
  });
  loadPosition();
};
const onSelectFloor = (value: string) => {
  console.log('onSelectFloor', value);
  loadPosition();
};

const onSearchPosition = (searchText: string) => {
  console.log('onSearchPosition', searchText);
  positionOptions.value = positionList.value.filter(s => s.position.indexOf(searchText) > -1).map(s => {
    console.log('target floor', s)
    return {value: s.position}
  });
};
const onSelectPosition = (value: string) => {
  console.log('onSelectFloor', value);
};
const loadFloor = async () => {
  const res = await listFloorApi({clientId: curClientId.value});
  console.log('loadFloor', res)
  floorList.value = res;
  floorOptions.value = floorList.value.map(s => {
    console.log('target floor', s)
    return {value: s.floor}
  });
}
const loadPosition = async () => {
  const res = await listPositionApi({clientId: curClientId.value, floorName: formState.floorName});
  console.log('loadPosition', res)
  positionList.value = res;
  positionOptions.value = positionList.value.map(s => {
    console.log('target floor', s)
    return {value: s.position}
  });
}
const handleChangeClient = () => {
  loadFloor();
}

const showAddAsset = () => {
  listClient()
  openAddAsset.value = true
}

const handleDetail = (record) => {
  targetAsset.value = record
  refreshKey.value = Math.random();
  openLifecycle.value = true
}

const handleShowOutbound = () => {
  refreshKey.value = Math.random();
  openOutbound.value = true
}
</script>
<style lang="less">
.basic-wrap {
  margin: 0 16px;
}

.button-wrap {
  margin: 16px 0;
  display: flex;
}

.right-button-wrap {
  margin-left: auto;
}

.hidden {
  display: none;
}
</style>
